package com.jdkreader.concurrency.concurrent.pipeline;

import java.util.concurrent.BrokenBarrierException;

/**
 * 流水线机器抽象类
 */
public abstract class Robot implements Runnable{

    private RobotPool pool;

    private boolean engage=false;

    protected Assembler assembler;

    public Robot(RobotPool rp){
        pool=rp;
    }

    public Robot assignAssembler(Assembler assembler){
        this.assembler=assembler;
        return this;
    }
    //不同的机器实现自己不同的功能
    public abstract void performService();

    public synchronized void engage(){
        engage=true;
        notifyAll();
    }

    private synchronized void powerDown() throws InterruptedException{
        engage=false;
        assembler=null; // 与装配工断开连接
        pool.release(this);
        while(!engage){
           wait();
        }
    }

    public void run(){
        try{
            //初始化装配状态
            powerDown();
            while(!Thread.interrupted()){
                performService();
                assembler.barrier().await();
                //工作完成，初始化状态
                powerDown();
            }
        }catch(InterruptedException e){
            System.out.println("Exiting "+this+" via interrupt");
            e.printStackTrace();
        }catch(BrokenBarrierException e){
            throw new RuntimeException(e);
        }

        System.out.println(this+" off ");
    }

    public String toString(){
        return getClass().getName();
    }

}
